<template>
  <div>
    <div class="tip">
      <div>订单提交成功，请尽快付款</div>
      <div style="display: flex"
        >请您在<el-countdown
          v-if="!expired"
          :value="endTime"
          class="countdown"
          format="mm:ss"
          @finish="handleExpire"
        />内完成支付，否则订单会被自动取消</div
      >
    </div>

    <div class="content">
      <p>订单号： {{ useTemporaryData.getPayOrdersNo() }}</p>
      <p>套餐名称：{{ comboData?.thaliName }}</p>
      <p
        >应付金额：<span class="price">￥{{ comboData?.price }}</span></p
      >

      <div class="qr-wrapper">
        <div v-if="qrValue" class="qr-box">
          <qrcode-vue :value="qrValue" :size="200" />

          <!--          <div v-if="loadingScan" class="overlay">-->
          <!--            <el-icon class="loading-icon"><Loading /></el-icon>-->
          <!--            <span>正在确认支付...</span>-->
          <!--          </div>-->

          <div v-if="expired" class="overlay">
            <p>二维码已过期</p>
            <el-button size="small" type="primary" @click="refreshQr">点击刷新</el-button>
          </div>
        </div>
      </div>

      <img src="@/assets/img/wx-pay.png" class="pay-logo" />
    </div>

    <div class="step-btn">
      <el-button type="default" @click="prevStep">上一步</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
  import QrcodeVue from 'qrcode.vue'
  import { ref, onMounted, onUnmounted } from 'vue'
  import { ElMessageBox, ElMessage } from 'element-plus'
  // import { Loading } from '@element-plus/icons-vue'
  import { getQrCode, getPaymentStatus } from '@/api/ApiList'
  import { useTemporaryStore } from '@/store/modules/temporary'

  const useTemporaryData = useTemporaryStore()
  const emit = defineEmits(['back', 'success'])

  const comboData = ref<any>(useTemporaryData.getChooseDrivingSchoolCombo())
  const qrValue = ref<string>()
  // const loadingScan = ref(false)
  const expired = ref(false)
  const endTime = ref(Date.now() + 15 * 60 * 1000)
  const router = useRouter()

  let timer: any = null

  async function getQrCodeData() {
    if (!useTemporaryData.getPayOrdersNo()) return

    expired.value = false
    // loadingScan.value = false
    endTime.value = Date.now() + 15 * 60 * 1000

    const res = await getQrCode({
      ordersNo: useTemporaryData.getPayOrdersNo()
    })
    if (res.code === '00000') {
      qrValue.value = res.data.codeUrl
      startPolling()
    } else {
      ElMessageBox.confirm(res.msg, 'Warning', {
        showCancelButton: false,
        type: 'warning'
      }).then(() => {
        router.push('/drivingSchoolConsole/schoolConsole')
      })
    }
  }

  function prevStep() {
    emit('back')
  }

  function startPolling() {
    stopPolling()
    timer = setInterval(() => {
      getPayStatus()
    }, 3000)
  }

  async function getPayStatus() {
    try {
      const res = await getPaymentStatus({
        ordersNo: useTemporaryData.getPayOrdersNo()
      })
      if (res.code === '00000') {
        const status = res.data.status
        if (status === 1) {
          stopPolling()
          ElMessage.success('支付成功')
          emit('success')
        } else if (status === 0) {
          // loadingScan.value = true
        }
      } else {
        stopPolling()
      }
    } catch {
      stopPolling()
    } finally {
    }
  }

  function stopPolling() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  function handleExpire() {
    expired.value = true
    stopPolling()
  }

  function refreshQr() {
    getQrCodeData()
  }

  onMounted(() => {
    if (!useTemporaryData.getPayOrdersNo()) {
      router.push('/drivingSchoolConsole/add')
    }
    getQrCodeData()
  })

  onUnmounted(() => {
    stopPolling()
  })
</script>

<style scoped lang="scss">
  .tip {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: var(--el-color-primary-light-9);
    color: var(--el-color-primary);

    .countdown {
      :deep(.el-statistic__number) {
        color: var(--el-color-primary);
      }
    }
  }

  .content {
    padding: 20px 0;
    display: flex;
    align-items: center;
    flex-direction: column;

    p {
      margin-bottom: 20px;
    }

    .price {
      color: red;
    }

    .pay-logo {
      width: 100px;
      margin-top: 10px;
    }
  }

  .qr-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;

    .qr-box {
      position: relative;
      width: 200px;
      height: 200px;
      margin-bottom: 10px;
    }

    .overlay {
      position: absolute;
      inset: 0;
      background: rgba(255, 255, 255, 0.85);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .loading-icon {
        animation: spin 1s linear infinite;
        font-size: 24px;
        margin-bottom: 6px;
      }
    }
  }

  .step-btn {
    display: flex;
    justify-content: center;
    align-items: center;

    margin-top: 20px;
  }

  @keyframes spin {
    100% {
      transform: rotate(360deg);
    }
  }
</style>
